package com.itic.ht.cms.question.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.framework.common.constants.Constants;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.UserSessionHelper;
import com.itic.ht.cms.exam.service.ExamService;
import com.itic.ht.cms.question.persistence.model.QuestionModel;
import com.itic.ht.cms.question.persistence.model.QuestionModelExample;
import com.itic.ht.cms.question.persistence.model.QuestionModelExample.Criteria;
import com.itic.ht.cms.question.service.QuestionModelService;
import com.itic.ht.cms.questype.persistence.model.QuestionType;
import com.itic.ht.cms.questype.persistence.model.QuestionTypeExample;
import com.itic.ht.cms.questype.service.QuestionTypeService;


@Controller
@RequestMapping(value="/cms/question")
public class QuestionModelController
     extends BaseController {
	@Autowired
	private ExamService examService;
	@Autowired
	protected QuestionTypeService questionTypeService;
	@Autowired
	protected QuestionModelService questionModelService;
    @Autowired
   	protected OutCommonService outCommonService;
       
       //////////////////////////////////////////////////////常量区////////////////////////////////////////////////////////////////
       private static final String MODEL_NAME_CHINA = "题库";//中文名
       private static final String MODEL_NAME＿ENGLISH = "question";//英文名
       private static final String PAGE_COMMON_PATH = "/cms/question/question";//通用路径
       private static final String PARENT_COMMON_URL = "/cms/questype/";//通用路径
       private static final String SUB_COMMON_URL = "/cms/questionselection/";//通用路径
       private static final String COMMON_URL = "/cms/question/";//通用路径
       
       //////////////////////////////////////////////////////页面跳转区////////////////////////////////////////////////////////////
      
       /*
        * 主页面
        */
       @RequestMapping(value="/init")
       public String init(Model model){
       	model.addAttribute("name_china", MODEL_NAME_CHINA);
       	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
       	model.addAttribute("parent_common_url", PARENT_COMMON_URL);
       	model.addAttribute("sub_common_url", SUB_COMMON_URL);
       	model.addAttribute("common_url", COMMON_URL);
       	return PAGE_COMMON_PATH+"Main";
       }
       
       /*
        * 主页面
        */
       @RequestMapping(value="/initList")
       public String initList(String categoryId,Model model){
       	model.addAttribute("categoryId", categoryId);
       	QuestionType questionType = questionTypeService.get(categoryId);
       	model.addAttribute("categoryIdName", questionType.getName());
       	model.addAttribute("name_china", MODEL_NAME_CHINA);
       	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
       	model.addAttribute("parent_common_url", PARENT_COMMON_URL);
       	model.addAttribute("sub_common_url", SUB_COMMON_URL);
       	model.addAttribute("common_url", COMMON_URL);
       	return PAGE_COMMON_PATH+"List";
       }
       
       /*
        * 添加页面
        */
       @RequestMapping(value="/initAdd")
       public String initAdd(String categoryId,Model model){
       	if( StringHelper.isNotBlank(categoryId) ){
       		model.addAttribute("categoryId", categoryId);
       	}
       	model.addAttribute("name_china", MODEL_NAME_CHINA);
       	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
       	model.addAttribute("parent_common_url", PARENT_COMMON_URL);
       	model.addAttribute("sub_common_url", SUB_COMMON_URL);
       	model.addAttribute("common_url", COMMON_URL);
       	return PAGE_COMMON_PATH+"Add";
       }
       
       /*
        * 编辑页面
        */
       @RequestMapping(value="/initEdit")
       public String initEdit(String id , String categoryId, Model model){
       	if( StringHelper.isNotBlank(id) ) {
       		QuestionModel temp = questionModelService.get(id);
       		model.addAttribute("editData",iticJsonMapper.toJson(temp));
       		model.addAttribute("name_china", MODEL_NAME_CHINA);
           	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
           	model.addAttribute("parent_common_url", PARENT_COMMON_URL);
           	model.addAttribute("sub_common_url", SUB_COMMON_URL);
           	model.addAttribute("common_url", COMMON_URL);
           	model.addAttribute("categoryId", categoryId);
       	}else {
               throw new ParameterErrorException();
           }
       	return PAGE_COMMON_PATH+"Edit";
       }
       
       /*
        * 查看页面
        */
       @RequestMapping(value="/initView")
       public String initView(String id , String categoryId, Model model){
       	if( StringHelper.isNotBlank(id) ) {
       		
       		QuestionModel temp  = questionModelService.get(id);
    		
       		model.addAttribute("product",iticJsonMapper.toJson(temp));
       		
       		QuestionModelExample example = new QuestionModelExample();
       		example.setOrderByClause("IS_MAIN desc");
       		Criteria criteria = example.createCriteria();
       		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
       		criteria.andCategoryEqualTo(id);
       		List<QuestionModel> list = questionModelService.list(example);
       		model.addAttribute("productSkus",iticJsonMapper.toJson(list));
       		
       		model.addAttribute("name_china", MODEL_NAME_CHINA);
           	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
           	model.addAttribute("parent_common_url", PARENT_COMMON_URL);
           	model.addAttribute("sub_common_url", SUB_COMMON_URL);
           	model.addAttribute("common_url", COMMON_URL);
           	model.addAttribute("categoryId", categoryId);
           	
       	}else {
               throw new ParameterErrorException();
           }
       	
       	return PAGE_COMMON_PATH+"View";
       }
       
       /*
        * 导入页面
        */
       @RequestMapping(value="/initImp")
       public String initImp(Model model){
       	model.addAttribute("name_china", MODEL_NAME_CHINA);
       	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
       	model.addAttribute("parent_common_url", PARENT_COMMON_URL);
       	model.addAttribute("sub_common_url", SUB_COMMON_URL);
       	model.addAttribute("common_url", COMMON_URL);
       	return PAGE_COMMON_PATH+"Imp";
       }
       
       
       //////////////////////////////////////////////////////业务代码区////////////////////////////////////////////////////////////
       
       /**
        * 添加模板管理数据
        * @param android
        * @return
        */
       @RequestMapping(value="/add")
       @ResponseBody
       public Map<String,String> add(QuestionModel templet){
       	
           	if(!"".equals(templet.getStyleText())){
        		String unescapeXml = StringEscapeUtils.unescapeXml(templet.getStyleText());
        		templet.setStyleText(unescapeXml);
        	}
       	    Map<String, String> resultMap = new HashMap<String, String>();
            String result = ResponseCode.SERVER_ERROR.getCode();
            
            //判断是添加新的商品还是  只添加一个SKU商品
            if(  StringHelper.isNotBlank(templet.getId()) ){

            }else{
            	String productId = IdGen.uuid();
            	Date date = new Date();
            	
            	//产品的必填字段
            	templet.setId(productId);
            	templet.setSelectionNum(0);
            	templet.setIsEffective(DBConst.TRUE);
            	templet.setCreateTime(date);
            	templet.setUpdateTime(date);
            	templet.setCreateUser(null != UserSessionHelper.get(Constants.USER_ID) ? UserSessionHelper.get(Constants.USER_ID) : "unknown");
            	templet.setOrgCode(null != UserSessionHelper.get(Constants.USER_ORG) ? UserSessionHelper.get(Constants.USER_ORG) : "unknown");
            	result = questionModelService.add(templet);
            }
            
            resultMap.put(IticConst.RESULT, result);
            resultMap.put(IticConst.DATA, templet.getCategory());//将问题的类型返回前端页面
            return resultMap;
            
            //别忘记了添加分类的商品统计 
       }
       
       
       /**
        * <p>Title:queryCondition </p>
        * <p>Description:封装查询条件 </p>
        * @param jzdw
        * @param jzdwExample
        * @return
        */
       private QuestionModelExample queryCondition(HttpServletRequest request,QuestionModel temp) {
       	
       	   // 参数处理
    	   QuestionModelExample example = new QuestionModelExample();
           // 按创建时间倒序
           example.setOrderByClause("create_time desc");
           // 按排列号顺序
           example.setOrderByClause("reorder asc");
           
           Criteria criteria = example.createCriteria().andIsEffectiveEqualTo( DBConst.TRUE );
           //
           criteria.andCategoryIdEqualTo(temp.getCategoryId());
           // 查询条件
           if ( null != temp ) {
        	   //过虑类别条件
        	   if ( StringHelper.isNotBlank( temp.getCategory() ) ) {
        		   criteria.andCategoryEqualTo(temp.getCategory());
        	   }
       	       //模糊查询
               if ( StringHelper.isNotBlank( temp.getName() ) ) {
                   criteria.andNameLike("%" + temp.getName() + "%");
               }
               
           }
           return example;
       }
       
       /**
        * 
        * @param goldType
        * @param request
        * @return
        */
       @RequestMapping(value = "/list")
       @ResponseBody
       public Map<String, Object> list(QuestionModel temp, HttpServletRequest request){
           // 声明返回对象
           Map<String, Object> resultMap = new HashMap<String, Object>();
           
           QuestionModelExample example = this.queryCondition(request,temp);
           // 封装分页参数
           example = this.handlePageQuery(request, example);
           
           // 获取信息总条数
           int total = questionModelService.count(example);
           
           // 获取数据
           List<QuestionModel> list = questionModelService.list(example);
           
           // 数据返回处理
           resultMap.put(IticConst.TOTAL_RECORDS, total);
           resultMap.put(IticConst.DISPLAY_RECORDS, total);
           resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
           resultMap.put(IticConst.DATA, list);
           return resultMap;

       }
       
       @RequestMapping(value="/edit")
       @ResponseBody
       public Map<String,String> edit(QuestionModel temp){
       
          	if(!"".equals(temp.getStyleText())){
       		     String unescapeXml = StringEscapeUtils.unescapeXml(temp.getStyleText());
       		     temp.setStyleText(unescapeXml);
       	    }
       	    Map<String, String> resultMap = new HashMap<String, String>();
            String result = ResponseCode.SERVER_ERROR.getCode();
            result = questionModelService.edit(temp);
            
            resultMap.put(IticConst.RESULT, result);
            return resultMap;
       }
       
       

       /**
        * 删除
        * 
        */
       @RequestMapping(value = "/del")
       @ResponseBody
       public Map<String, String> del(String id) {
           Map<String, String> resultMap = new HashMap<String, String>();
           String result = ResponseCode.SERVER_ERROR.getCode();

           //删除一个
           //当前商品的数量减一
//           QuestionModel product = questionModelService.get(id);
           
           //更新这个类型下的问题的总个数
/*           
           QuestionType category = questionTypeService.get(product.getCategory());
           if( null != category ){
        	   String count = "0";
               if( StringHelper.isNotBlank(category.getCount()) ){
            	   count = category.getCount();
               }
               count = NumberStringHelper.subtractString(count, "1");
               category.setCount(count);
           }*/
           
           if( StringHelper.isNotBlank(id) ){
        	   QuestionModel temp = new QuestionModel();
               temp.setId(id);
               temp.setIsEffective(DBConst.FALSE);
               result = questionModelService.delete(temp);
           }
           
           resultMap.put(IticConst.RESULT, result);
           return resultMap;
       }
       
       /**
        * 获取全部类型
        * 
        */
       @RequestMapping(value = "/getQuestionTypes")
       @ResponseBody
       public List<QuestionType> getQuestionTypes() {
    	  QuestionTypeExample example = new QuestionTypeExample();
          example.setOrderByClause("reorder asc");
          example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
          List<QuestionType> list = questionTypeService.list(example);
          return list;
       }

       
}